import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { _HttpClient, ModalHelper, SettingsService } from '@delon/theme';
import * as moment from 'moment';
import { NzCascaderOption } from 'ng-zorro-antd/cascader';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { zip } from 'rxjs';
import { finalize } from 'rxjs/operators';

export interface ShopFlowSourceTreeNode {
  source_id: string;
  source: {};
  ctm_item_click_uv?: number;
  ctm_item_click_uv_compare?: number;
  item_cart_uv?: number;
  item_cart_uv_compare?: number;
  order_uv?: number;
  order_uv_compare?: number;
  ctm_order_view_rate?: number;
  ctm_order_view_rate_compare?: number;
  level?: number;
  expand?: boolean;
  children?: ShopFlowSourceTreeNode[];
  parent?: ShopFlowSourceTreeNode;
}

@Component({
  selector: 'app-business-netflow',
  templateUrl: './netflow.component.html',
  styleUrls: ['./netflow.component.less']
})
export class BusinessNetflowComponent implements OnInit {
  loading = true;
  isAdmin = false;
  q: {
    shopId: number;
    dateType: number;
    dateVal: string;
  } = {
    shopId: 0,
    dateType: 1,
    dateVal: moment().subtract(1, 'days').format('YYYY-MM-DD')
    // dateVal: '2023-03-06'
  };
  statistics_date = this.q.dateVal;
  compareText = '较前一日';
  shops = [];

  listOfMapData: ShopFlowSourceTreeNode[] = [];
  mapOfExpandedData: { [source_id: string]: ShopFlowSourceTreeNode[] } = {};
  waresFlowRank = [];
  shopTrans = [];

  collapse(array: ShopFlowSourceTreeNode[], data: ShopFlowSourceTreeNode, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.source_id === d.source_id)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: ShopFlowSourceTreeNode): ShopFlowSourceTreeNode[] {
    const stack: ShopFlowSourceTreeNode[] = [];
    const array: ShopFlowSourceTreeNode[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });

    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: ShopFlowSourceTreeNode, hashMap: { [source_id: string]: boolean }, array: ShopFlowSourceTreeNode[]): void {
    if (!hashMap[node.source_id]) {
      hashMap[node.source_id] = true;
      array.push(node);
    }
  }

  constructor(private http: _HttpClient, private cdr: ChangeDetectorRef, private router: Router, private settingService: SettingsService) {
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
    }
    //let uri = `api/shop_map`;
    let uri = `api/shop_map_full`;
    this.http.get(uri).subscribe(res => {
      this.genCompanyShopOptions(res.data['companies'], res.data['shops']);
      // @ts-ignore
      this.q.shopId = this.values[1];
      this.loadDataFromServer();
      this.cdr.detectChanges();
    });
  }

  ngOnInit(): void {
    console.log(this.listOfMapData);
    // this.listOfMapData.forEach(item => {
    //   this.mapOfExpandedData[item.source_id] = this.convertTreeToList(item);
    // });
  }

  loadDataFromServer(): void {
    this.loading = true;
    zip(this.http.get(`api/shop/trans`, this.q), this.http.get(`api/shop_flow_source`, this.q), this.http.get(`api/item_flow_rank`, this.q))
      .pipe(
        finalize(() => {
          this.cdr.detectChanges();
        })
      )
      .subscribe(([trans, shopFlowSource, waresFlowRank]: [NzSafeAny, NzSafeAny, NzSafeAny]) => {
        if (trans.data) {
          // @ts-ignore
          this.shopTrans = [trans.data];
        }
        this.waresFlowRank = waresFlowRank.data;
        this.listOfMapData = shopFlowSource.data;
        if (this.listOfMapData) {
          this.listOfMapData.forEach(item => {
            this.mapOfExpandedData[item.source_id] = this.convertTreeToList(item);
          });
        }
        this.loading = false;
        this.cdr.detectChanges();
      });
  }

  dateTypeChange(value: number) {
    this.q.dateVal = '';
    let yesterday = moment().subtract(1, 'days').format('YYYY-MM-DD');
    if (value == 1) {
      this.statistics_date = yesterday;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前一日';
    } else if (value == 2) {
      this.statistics_date = `${moment().subtract(7, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前7日';
    } else if (value == 3) {
      this.statistics_date = `${moment().subtract(30, 'days').format('YYYY-MM-DD')}~${yesterday}`;
      this.q.dateVal = this.statistics_date;
      this.loadDataFromServer();
      this.compareText = '较前30日';
    } else if (value == 5) {
      this.compareText = '较前一月';
    } else if (value == 4) {
      this.compareText = '较前一日';
    }
  }

  datePickerChange(value: any) {
    if (this.q.dateType == 4) {
      this.q.dateVal = moment(value).format('yyyy-MM-DD');
    } else if (this.q.dateType == 5) {
      this.q.dateVal = moment(value).format('yyyy-MM');
    }
    this.statistics_date = this.q.dateVal;
    this.loadDataFromServer();
  }

  view(shopId: number, itemId: number) {
    console.log('redirect');
    this.router.navigate([`/business/ware-analysis`], {
      queryParams: {
        shopId: shopId,
        itemId: itemId,
        dateType: this.q.dateType,
        dateVal: this.q.dateVal
      }
    });
  }

  companyShopOptions: NzCascaderOption[] | null = [];
  values: any[] | null = null;

  genCompanyShopOptions(companies: any[], shops: any[]): void {
    let companyList: NzCascaderOption[] = [];
    companies.forEach((company: { ID: number; company_name: string }) => {
      let companyShopItem: NzCascaderOption = {
        value: company.ID,
        label: this.isAdmin ? company.company_name : '***',
        companyId: company.ID,
        isLeaf: false,
        children: [],
        disabled: true
      };
      companyList.push(companyShopItem);
    });
    companyList.forEach(company => {
      shops.forEach((shop: { shop_id: number; company_id: number; fordeal_shop_name: string }) => {
        if (shop.company_id == company.value) {
          let companyShopItem: NzCascaderOption = {
            value: shop.shop_id,
            label: shop.fordeal_shop_name,
            companyId: company.value,
            isLeaf: true,
            disabled: false
          };
          company.disabled = false;
          // @ts-ignore
          company.children.push(companyShopItem);
        }
      });
    });
    // @ts-ignore
    this.values = [companyList[0].value, companyList[0].children[0].value];
    this.companyShopOptions = companyList;
  }

  onChanges(values: any) {
    this.q.shopId = values[1];
    this.loadDataFromServer();
  }
}
